<!--
 * @author: sanbao
 * @Date: 2022-08-14 20:21:35
-->
<template>
  <div>
    <el-upload
      class="upload-demo"
      action=""
      drag
      :auto-upload="false"
      :on-change="uploadChange"
      :limit="1"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    </el-upload>
  </div>
</template>
<script>
import { defineComponent, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import * as XLSX from "xlsx"; // vue3可用此引入
import { userBatchImport } from "../../api/userManage.ts";
export default defineComponent({
  name: "upload",
  setup() {
    const tableData = ref([]);
    const router = useRouter();
    const uploadChange = async (e) => {
      console.log(e);
      const files = e.raw;
      if (files.length <= 0) {
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files.name.toLowerCase())) {
        console.log("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }
      // 读取表格
      const fileReader = new FileReader();
      fileReader.onload = (ev) => {
        const workbook = XLSX.read(ev.target.result, {
          type: "binary",
        });
        const wsname = workbook.SheetNames[0];
        const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);
        console.log(ws); // 转换成json的数据
        const m = dealExcel(ws); // ...对数据进行自己需要的操作
        console.log(m);
        tableData.value = m;

        userBatchImportImport();
      };
      fileReader.readAsBinaryString(files);
    };
    const dealExcel = (ws) => {
      let keymap = {
        // 我们要转换的开头
        姓名: "username",
        联系方式: "mobile",
        开通时间: "openTime",
      };
      ws.forEach((sourceObj) => {
        let arr = new Array();
        Object.keys(sourceObj).map((keys) => {
          if (keys.includes("步骤")) {
            arr.push(sourceObj[keys]);
            delete sourceObj[keys];
          } else if (keymap[keys]) {
            sourceObj[keymap[keys]] = sourceObj[keys];
            delete sourceObj[keys];
          }
        });
        sourceObj["steps"] = arr;
      });
      return ws;
    };

    const userBatchImportImport = async () => {
      try {
        const res = await userBatchImport(tableData.value);
        console.log(res);
        ElMessage.success("批量导入成功"); // 提示错误信息
        router.go(-1);
      } catch (error) {}
    };

    return {
      uploadChange,
    };
  },
});
</script>
<style scoped lang="scss"></style>
